<template>
	<view class="addQues">
		<view class="uploadModule">
			<view class="rich">
				<view class="richTitle">
					<textarea placeholder-class="font14" v-model.trim="title" class="bold font18" maxlength="50" auto-height
						placeholder="请输入醒目的标题"></textarea>
				</view>
				<view class="richCon">
					<editor id="editor" class="font14" :placeholder="placeholderTxt" @ready="onEditorReady"
						@input="accountText"></editor>
					<view :class="textCount.length>100?'font14 txt colorRed bold':'font14 txt color666'">{{textCount.length}}/100
					</view>
				</view>
				<!-- 是否公开 -->
				<view class="openBox">
					<radio-group class="flex alignCenter" @change="changeOpenStatus">
						<label class="flex alignCenter labelItem" v-for="(item, index) in openArr" :key="item.value">
							<view>
								<radio class="radioActive" style="transform:scale(0.7)" color="#F7DD5E" :value="item.value"
									:checked="item.value == isPublic" />
							</view>
							<view class="font14">{{item.name}}</view>
						</label>
					</radio-group>
				</view>
				<!-- 发送到圈子 -->
				<view class="isCircle">
					<uni-mdlist :listData="itemArr" @clickItem="clickItem"></uni-mdlist>
					<!-- <uni-mdlist :listData="itemAr" @clickItem="clickItem"></uni-mdlist> -->
				</view>
			</view>
			<view class="flex alignCenter justConBetween uploadOper">
				<image src="@/static/image/icons/pic.png" mode="widthFix" @click="uploadFileClick"></image>
				<view class="flex alignCenter" v-if="quesType!='note'">
					<text class="bold font16" v-if="bounty">{{bounty}}元</text>
					<image src="@/static/image/icons/b.png" mode="widthFix" @click="showReward"></image>
				</view>
			</view>
			<uni-imgbox v-if="imgUrl.length>0" :imgArr="imgUrl"></uni-imgbox>
		</view>
		<view class="fixedBottomBtn" @click="submitClick"><i class="iconfont icon-fabu"></i>提交</view>
		<!-- 赏金 -->
		<uni-reward :rewardStatus="rewardStatus" @closeReward="closeReward"
			@chooseRewardSucc="chooseRewardSucc"></uni-reward>
	</view>
</template>

<script>
	import {
		addQues,
		addTaskNote
	} from "@/api/send.js"
	import {
		uploadFile,
		chooseImg
	} from "@/utils/common.js"
	import uniReward from "@/pages/send/components/uni-reward/uni-reward.vue"
	export default {
		components: {
			uniReward
		},
		data() {
			return {
				placeholderTxt:"让问题尽可能精彩，让更多的人想来看你的答案",
				imgUrl: [],
				editorCtx: '',
				title: '',
				content: '',
				warningCon: '',
				rewardStatus: false,
				isPublic: 1,
				openArr: [{
					name: '公开',
					value: '1'
				}, {
					name: '不公开',
					value: '0'
				}],
				itemArr: [{
					title: '发送到圈子',
					icon: '/static/image/setting/major.png',
					subTitle: '更容易被发现',
					val: '',
					type: 'circle'
				}, {
					title: '关联到话题',
					icon: '/static/image/floatBtn/q.png',
					subTitle: '获得优先推荐~',
					val: '',
					type: 'knowledge'
				}, {
					title: '归类到知识体系',
					icon: '/static/image/setting/cat.png',
					subTitle: '获得优先推荐~',
					val: '',
					type: 'knowledge'
				}, ],
				// 选择的圈子
				chooseCircle: [],
				// 选择的赏金
				bounty: '',
				fromPage: '', //seniorSister、提问学长学姐
				navTitle: '提问',
				// 提问类型
				quesType: '',
				groupId: '',
				// 统计内容个数
				textCount: '',
				seniorSisterId: '', //学长学姐id
			}
		},
		onLoad(option) {
			this.fromPage = option.from;
			if (this.fromPage == 'task') {
				this.taskId = option.id
				this.quesType = option.type ? option.type : ''
				// 从小组到任务到任务的提问打卡，需要带上小组id
				this.groupId = (option.groupId && option.groupId != undefined) ? option.groupId : ''
				this.navTitle = `${option.type=='ques'?'提问任务：':'打卡任务：'}` + option.title;
				this.placeholderTxt = option.type=='ques'? '让问题尽可能精彩，让更多的人想来看你的答案' : "记录下每一个闪光的片段，累计成江河。"
				uni.setNavigationBarTitle({
					title: this.navTitle
				})
			}
			// 提问学长学姐
			if (this.fromPage == 'seniorSister') {
				this.seniorSisterId = option.id; // 学长学姐id
				this.navTitle = `对${option.title}提问`;
				uni.setNavigationBarTitle({
					title: this.navTitle
				})
			}
		},
		onShow() {
			this.chooseCircle = uni.getStorageSync('chooseCircle') || []
			this.itemArr[0].val = `已选${this.chooseCircle.length}个`
		},
		onUnload() {
			uni.removeStorageSync('chooseCircle')
		},
		methods: {
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},
			// 统计富文本字数个数
			accountText(e) {
				this.textCount = e.detail.text.replace('\n', '')
			},
			uploadFileClick() {
				if (this.imgUrl.length >= 9) {
					uni.showToast({
						title: '图片最多9张',
						icon: 'none'
					})
					return
				}
				chooseImg(9).then((res) => {
					console.error("res", res)
					res.forEach((item) => {
						uploadFile([item]).then((successFile) => {
							console.log('文件', successFile)
							this.imgUrl.push(successFile.url)
						})
					})
				})
			},
			// 删除图片
			delPic(idx) {
				this.imgUrl.splice(idx, 1)
			},
			// 预览图片
			showBigPic(idx) {
				uni.previewImage({
					current: idx,
					urls: this.imgUrl,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			// 是否公开
			changeOpenStatus(e) {
				this.isPublic = e.detail.value
				if (this.isPublic == 0) {
					this.itemArr = [{
						title: '归类到知识体系',
						icon: '/static/image/setting/cat.png',
						subTitle: '获得优先推荐~',
						val: '',
						type: 'knowledge'
					}]
				} else {
					this.itemArr = [{
						title: '发送到圈子',
						icon: '/static/image/setting/major.png',
						subTitle: '更容易被发现',
						val: '',
						type: 'circle'
					}, {
						title: '关联到话题',
						icon: '/static/image/floatBtn/q.png',
						subTitle: '获得优先推荐~',
						val: '',
						type: 'knowledge'
					}, {
						title: '归类到知识体系',
						icon: '/static/image/setting/cat.png',
						subTitle: '获得优先推荐~',
						val: '',
						type: 'knowledge'
					}, ]
				}
			},
			// 赏金
			showReward() {
				this.rewardStatus = true
			},
			closeReward() {
				this.rewardStatus = false
			},
			chooseRewardSucc(item) {
				console.log('悬赏金额', item)
				this.bounty = item.title
				this.closeReward()
			},
			// 圈子
			clickItem(item) {
				console.log('item===', item)
				if (item.type == 'circle') {
					uni.navigateTo({
						url: '/pages/school/circle/circle?circle=' + JSON.stringify(this.chooseCircle)
					})
				} else {
					uni.navigateTo({
						url: '/pages/send/knowledge/knowledge'
					})
				}

			},
			submitClick() {
				// 内容是纯文本的富文本编辑，非textarea时获取内容
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx.getContents({
						success: (res2) => {
							this.content = (res2.text != "\n" ? res2.html : '')
							console.log('res2', res2)

							if (!this.title) {
								uni.showToast({
									icon: 'none',
									title: '请输入标题！'
								})
								return
							}
							if (!this.content) {
								uni.showToast({
									icon: 'none',
									title: '请输入内容！'
								})
								return
							}
							if (this.textCount.length > 100) {
								uni.showToast({
									icon: 'none',
									title: '内容限制在100字符内！'
								})
								return
							}
							if (this.isPublic == 1 && this.chooseCircle.length == 0) {
								uni.showToast({
									icon: 'none',
									title: '公开提问需要选择要发送的圈子！'
								})
								return
							}
							uni.showLoading({
								title: '提交中',
								mask: true
							})
							let circle = []
							this.chooseCircle.forEach((item) => {
								let newP = {
									// circleId:item.circleId,
									objectId: item.objectId || item.subjectCode,
									objectName: item.circleName
								}
								circle.push(newP)
							})
							let param = {
								title: this.title,
								content: this.content,
								isPublic: this.isPublic,
								imgUrl: this.imgUrl.length > 0 ? this.imgUrl.join(',') : '',
								circles: this.isPublic == 1 ? circle : [],
								bounty: this.bounty
							}
							if (this.quesType == 'note') {
								// 打卡笔记
								param.taskId = this.taskId
								param.teamId = this.groupId
								addTaskNote(param).then((res) => {
									if (res.code == 100000) {
										uni.removeStorageSync('chooseCircle')
										uni.navigateBack({
											delta: 1
										})
									}
									uni.hideLoading()
								}).catch((err) => {
									uni.hideLoading()
								})
							} else {
								// 提问
								if (this.taskId) {
									// 提问任务
									param.taskId = this.taskId
									param.teamId = this.groupId
								}

								// 提问学长学姐
								if (this.seniorSisterId) {
									param.broAnswerId = this.seniorSisterId;
								}
								addQues(param).then((res) => {
									if (res.code == 100000) {
										uni.removeStorageSync('chooseCircle')
										if (this.fromPage == 'major') {
											uni.switchTab({
												url: '/pages/major/major'
											})
											return
										} else if (this.fromPage == 'school') {
											uni.switchTab({
												url: '/pages/schoolMain/schoolMain'
											})
											return
										} else if (this.fromPage == 'task') {
											uni.navigateBack({
												delta: 1
											})
											return
										} else {
											uni.showToast({
												title: '提问成功',
												icon: 'none'
											})
											setTimeout(() => {
												uni.navigateBack()
											}, 1500)
										}

									}
									uni.hideLoading()
								}).catch((err) => {
									uni.hideLoading()
								})
							}
						},
						fail: (err) => {
							uni.showToast({
								title: '获取内容出错',
								icon: 'none'
							})
						}
					})
				}).exec()
			},
		}
	}
</script>

<style scoped lang="scss">
	.addQues {
		padding: 0 0 120rpx;
		background-color: #F6F8F6;
		height: 90vh;
	}

	.uploadOper {
		border-top: 1px solid $bordercolor;
		border-bottom: 1px solid $bordercolor;
		padding: 20rpx 30rpx;
		box-sizing: border-box;

		image {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.imgBox {
		.picItem {
			position: relative;
			width: 100%;
			height: 100%;
		}

		.pic {
			width: 100%;
			height: 100%;
			display: block;
		}

		.picLayer {
			position: absolute;
			width: 100%;
			height: 100%;
			top: 0;
			left: 0;
			background: rgba(0, 0, 0, .3);
			color: #fff;
			padding: 0 40rpx;
			box-sizing: border-box;
		}
	}

	.rich {
		box-sizing: border-box;

		.richTitle {
			textarea {
				width: 100%;
				margin-left: 30rpx;
			}

			background-color: #fff;
			padding: 20rpx 0;
			border-bottom: 1px solid $bordercolor;
		}

		.richCon {
			position: relative;
			background-color: #fff;

			.txt {
				text-align: right;
				margin-right: 30rpx;
			}

			textarea {
				width: 100%;
				padding: 20rpx 0;
				box-sizing: border-box;
			}

			#editor {
				width: 100%;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
			}
		}

		.openBox {
			background-color: #fff;
			padding-left: 30rpx;
			padding-bottom: 10rpx;
		}

		.labelItem {
			margin-right: 50rpx;
		}
	}

	::v-deep .radioActive .uni-radio-input-checked {
		background-color: $colorMain !important;
		border-color: $colorMain !important;
	}

	.isCircle {
		margin-top: 20rpx;

		::v-deep .listItem {
			padding-left: 0;
			padding-right: 0;
			border: none;
		}
	}
</style>